package com.sangmo.boot.auth.core.model;

import com.sangmo.boot.framework.data.entity.guid.GuidEntity2;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;

@Entity
@Table(name = "client")
public class Client extends GuidEntity2 {

	@NotBlank
	private String name;
	@NotBlank
	private String secret;

	private String scope;

	private String resource;

	@NotBlank
	private String state = States.ENABLED;

	@NotBlank
	private String grantType = GrantTypes.PASSWORD;

	private long validity;

	public String getSecret() {
		return secret;
	}
	public void setSecret(String secret) {
		this.secret = secret;
	}
	public String getScope() {
		return scope;
	}
	public void setScope(String scope) {
		this.scope = scope;
	}

	public String getResource() {
		return resource;
	}

	public void setResource(String resource) {
		this.resource = resource;
	}

	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getGrantType() {
		return grantType;
	}
	public void setGrantType(String grantType) {
		this.grantType = grantType;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getValidity() {
		return validity;
	}
	public void setValidity(long validity) {
		this.validity = validity;
	}

	public boolean containsGrantType(String grantType) {
		if(StringUtils.isEmpty(grantType)) {
			return true;
		}
		if(StringUtils.isEmpty(this.grantType)) {
			return false;
		}
		String[] clientGrantTypes = this.grantType.split(",", -1);
		return ArrayUtils.contains(clientGrantTypes, grantType);
	}

	public boolean containsResource(String resource) {
		if(StringUtils.isEmpty(resource)) {
			return true;
		}
		if(StringUtils.isEmpty(this.resource)) {
			return false;
		}
		String[] clientResources = this.resource.split(",", -1);
		String[] resourceArr = resource.split(",", -1);

		for (String s : resourceArr) {
			if (!ArrayUtils.contains(clientResources, s)) {
				return false;
			}
		}
		return true;
	}

	public boolean containsScope(String scope) {
		if(StringUtils.isEmpty(scope)) {
			return true;
		}
		if(StringUtils.isEmpty(this.scope)) {
			return false;
		}

		String[] clientScopes = this.getScope().split(",", -1);
		String[] scopeArr = scope.split(",", -1);
		for (String s : scopeArr) {
			if (!ArrayUtils.contains(clientScopes, s)) {
				return false;
			}
		}
		return true;
	}

	public interface GrantTypes {
		String CODE = "CODE";
		String PASSWORD = "PASSWORD";
		String CLIENT_CREDEDNTIAL = "CLIENT_CREDENTIAL";
		String OPENID = "OPENID";
		String WX_CODE = "WX_CODE";
	}

	public interface States {
		String ENABLED = "ENABLED";
		String DISABLED = "DISABLED";
	}
}
